/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.Currencies;
import pojos.SourceCode;
import java.util.ArrayList;
import java.util.Collection;
import pojos.Employees;
import pojos.Expenses;

/**
 *
 * @author A7med Kotb
 */
public class CurrenciesJpaController implements Serializable {

    public CurrenciesJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Currencies currencies) throws RollbackFailureException, Exception {
        if (currencies.getSourceCodeCollection() == null) {
            currencies.setSourceCodeCollection(new ArrayList<SourceCode>());
        }
        if (currencies.getEmployeesCollection() == null) {
            currencies.setEmployeesCollection(new ArrayList<Employees>());
        }
        if (currencies.getExpensesCollection() == null) {
            currencies.setExpensesCollection(new ArrayList<Expenses>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<SourceCode> attachedSourceCodeCollection = new ArrayList<SourceCode>();
            for (SourceCode sourceCodeCollectionSourceCodeToAttach : currencies.getSourceCodeCollection()) {
                sourceCodeCollectionSourceCodeToAttach = em.getReference(sourceCodeCollectionSourceCodeToAttach.getClass(), sourceCodeCollectionSourceCodeToAttach.getScId());
                attachedSourceCodeCollection.add(sourceCodeCollectionSourceCodeToAttach);
            }
            currencies.setSourceCodeCollection(attachedSourceCodeCollection);
            Collection<Employees> attachedEmployeesCollection = new ArrayList<Employees>();
            for (Employees employeesCollectionEmployeesToAttach : currencies.getEmployeesCollection()) {
                employeesCollectionEmployeesToAttach = em.getReference(employeesCollectionEmployeesToAttach.getClass(), employeesCollectionEmployeesToAttach.getEmpId());
                attachedEmployeesCollection.add(employeesCollectionEmployeesToAttach);
            }
            currencies.setEmployeesCollection(attachedEmployeesCollection);
            Collection<Expenses> attachedExpensesCollection = new ArrayList<Expenses>();
            for (Expenses expensesCollectionExpensesToAttach : currencies.getExpensesCollection()) {
                expensesCollectionExpensesToAttach = em.getReference(expensesCollectionExpensesToAttach.getClass(), expensesCollectionExpensesToAttach.getExpId());
                attachedExpensesCollection.add(expensesCollectionExpensesToAttach);
            }
            currencies.setExpensesCollection(attachedExpensesCollection);
            em.persist(currencies);
            for (SourceCode sourceCodeCollectionSourceCode : currencies.getSourceCodeCollection()) {
                Currencies oldCurrencyOfSourceCodeCollectionSourceCode = sourceCodeCollectionSourceCode.getCurrency();
                sourceCodeCollectionSourceCode.setCurrency(currencies);
                sourceCodeCollectionSourceCode = em.merge(sourceCodeCollectionSourceCode);
                if (oldCurrencyOfSourceCodeCollectionSourceCode != null) {
                    oldCurrencyOfSourceCodeCollectionSourceCode.getSourceCodeCollection().remove(sourceCodeCollectionSourceCode);
                    oldCurrencyOfSourceCodeCollectionSourceCode = em.merge(oldCurrencyOfSourceCodeCollectionSourceCode);
                }
            }
            for (Employees employeesCollectionEmployees : currencies.getEmployeesCollection()) {
                Currencies oldCurrencyOfEmployeesCollectionEmployees = employeesCollectionEmployees.getCurrency();
                employeesCollectionEmployees.setCurrency(currencies);
                employeesCollectionEmployees = em.merge(employeesCollectionEmployees);
                if (oldCurrencyOfEmployeesCollectionEmployees != null) {
                    oldCurrencyOfEmployeesCollectionEmployees.getEmployeesCollection().remove(employeesCollectionEmployees);
                    oldCurrencyOfEmployeesCollectionEmployees = em.merge(oldCurrencyOfEmployeesCollectionEmployees);
                }
            }
            for (Expenses expensesCollectionExpenses : currencies.getExpensesCollection()) {
                Currencies oldCurrencyOfExpensesCollectionExpenses = expensesCollectionExpenses.getCurrency();
                expensesCollectionExpenses.setCurrency(currencies);
                expensesCollectionExpenses = em.merge(expensesCollectionExpenses);
                if (oldCurrencyOfExpensesCollectionExpenses != null) {
                    oldCurrencyOfExpensesCollectionExpenses.getExpensesCollection().remove(expensesCollectionExpenses);
                    oldCurrencyOfExpensesCollectionExpenses = em.merge(oldCurrencyOfExpensesCollectionExpenses);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Currencies currencies) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Currencies persistentCurrencies = em.find(Currencies.class, currencies.getCurrId());
            Collection<SourceCode> sourceCodeCollectionOld = persistentCurrencies.getSourceCodeCollection();
            Collection<SourceCode> sourceCodeCollectionNew = currencies.getSourceCodeCollection();
            Collection<Employees> employeesCollectionOld = persistentCurrencies.getEmployeesCollection();
            Collection<Employees> employeesCollectionNew = currencies.getEmployeesCollection();
            Collection<Expenses> expensesCollectionOld = persistentCurrencies.getExpensesCollection();
            Collection<Expenses> expensesCollectionNew = currencies.getExpensesCollection();
            List<String> illegalOrphanMessages = null;
            for (SourceCode sourceCodeCollectionOldSourceCode : sourceCodeCollectionOld) {
                if (!sourceCodeCollectionNew.contains(sourceCodeCollectionOldSourceCode)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain SourceCode " + sourceCodeCollectionOldSourceCode + " since its currency field is not nullable.");
                }
            }
            for (Employees employeesCollectionOldEmployees : employeesCollectionOld) {
                if (!employeesCollectionNew.contains(employeesCollectionOldEmployees)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Employees " + employeesCollectionOldEmployees + " since its currency field is not nullable.");
                }
            }
            for (Expenses expensesCollectionOldExpenses : expensesCollectionOld) {
                if (!expensesCollectionNew.contains(expensesCollectionOldExpenses)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Expenses " + expensesCollectionOldExpenses + " since its currency field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<SourceCode> attachedSourceCodeCollectionNew = new ArrayList<SourceCode>();
            for (SourceCode sourceCodeCollectionNewSourceCodeToAttach : sourceCodeCollectionNew) {
                sourceCodeCollectionNewSourceCodeToAttach = em.getReference(sourceCodeCollectionNewSourceCodeToAttach.getClass(), sourceCodeCollectionNewSourceCodeToAttach.getScId());
                attachedSourceCodeCollectionNew.add(sourceCodeCollectionNewSourceCodeToAttach);
            }
            sourceCodeCollectionNew = attachedSourceCodeCollectionNew;
            currencies.setSourceCodeCollection(sourceCodeCollectionNew);
            Collection<Employees> attachedEmployeesCollectionNew = new ArrayList<Employees>();
            for (Employees employeesCollectionNewEmployeesToAttach : employeesCollectionNew) {
                employeesCollectionNewEmployeesToAttach = em.getReference(employeesCollectionNewEmployeesToAttach.getClass(), employeesCollectionNewEmployeesToAttach.getEmpId());
                attachedEmployeesCollectionNew.add(employeesCollectionNewEmployeesToAttach);
            }
            employeesCollectionNew = attachedEmployeesCollectionNew;
            currencies.setEmployeesCollection(employeesCollectionNew);
            Collection<Expenses> attachedExpensesCollectionNew = new ArrayList<Expenses>();
            for (Expenses expensesCollectionNewExpensesToAttach : expensesCollectionNew) {
                expensesCollectionNewExpensesToAttach = em.getReference(expensesCollectionNewExpensesToAttach.getClass(), expensesCollectionNewExpensesToAttach.getExpId());
                attachedExpensesCollectionNew.add(expensesCollectionNewExpensesToAttach);
            }
            expensesCollectionNew = attachedExpensesCollectionNew;
            currencies.setExpensesCollection(expensesCollectionNew);
            currencies = em.merge(currencies);
            for (SourceCode sourceCodeCollectionNewSourceCode : sourceCodeCollectionNew) {
                if (!sourceCodeCollectionOld.contains(sourceCodeCollectionNewSourceCode)) {
                    Currencies oldCurrencyOfSourceCodeCollectionNewSourceCode = sourceCodeCollectionNewSourceCode.getCurrency();
                    sourceCodeCollectionNewSourceCode.setCurrency(currencies);
                    sourceCodeCollectionNewSourceCode = em.merge(sourceCodeCollectionNewSourceCode);
                    if (oldCurrencyOfSourceCodeCollectionNewSourceCode != null && !oldCurrencyOfSourceCodeCollectionNewSourceCode.equals(currencies)) {
                        oldCurrencyOfSourceCodeCollectionNewSourceCode.getSourceCodeCollection().remove(sourceCodeCollectionNewSourceCode);
                        oldCurrencyOfSourceCodeCollectionNewSourceCode = em.merge(oldCurrencyOfSourceCodeCollectionNewSourceCode);
                    }
                }
            }
            for (Employees employeesCollectionNewEmployees : employeesCollectionNew) {
                if (!employeesCollectionOld.contains(employeesCollectionNewEmployees)) {
                    Currencies oldCurrencyOfEmployeesCollectionNewEmployees = employeesCollectionNewEmployees.getCurrency();
                    employeesCollectionNewEmployees.setCurrency(currencies);
                    employeesCollectionNewEmployees = em.merge(employeesCollectionNewEmployees);
                    if (oldCurrencyOfEmployeesCollectionNewEmployees != null && !oldCurrencyOfEmployeesCollectionNewEmployees.equals(currencies)) {
                        oldCurrencyOfEmployeesCollectionNewEmployees.getEmployeesCollection().remove(employeesCollectionNewEmployees);
                        oldCurrencyOfEmployeesCollectionNewEmployees = em.merge(oldCurrencyOfEmployeesCollectionNewEmployees);
                    }
                }
            }
            for (Expenses expensesCollectionNewExpenses : expensesCollectionNew) {
                if (!expensesCollectionOld.contains(expensesCollectionNewExpenses)) {
                    Currencies oldCurrencyOfExpensesCollectionNewExpenses = expensesCollectionNewExpenses.getCurrency();
                    expensesCollectionNewExpenses.setCurrency(currencies);
                    expensesCollectionNewExpenses = em.merge(expensesCollectionNewExpenses);
                    if (oldCurrencyOfExpensesCollectionNewExpenses != null && !oldCurrencyOfExpensesCollectionNewExpenses.equals(currencies)) {
                        oldCurrencyOfExpensesCollectionNewExpenses.getExpensesCollection().remove(expensesCollectionNewExpenses);
                        oldCurrencyOfExpensesCollectionNewExpenses = em.merge(oldCurrencyOfExpensesCollectionNewExpenses);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = currencies.getCurrId();
                if (findCurrencies(id) == null) {
                    throw new NonexistentEntityException("The currencies with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Currencies currencies;
            try {
                currencies = em.getReference(Currencies.class, id);
                currencies.getCurrId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The currencies with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<SourceCode> sourceCodeCollectionOrphanCheck = currencies.getSourceCodeCollection();
            for (SourceCode sourceCodeCollectionOrphanCheckSourceCode : sourceCodeCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Currencies (" + currencies + ") cannot be destroyed since the SourceCode " + sourceCodeCollectionOrphanCheckSourceCode + " in its sourceCodeCollection field has a non-nullable currency field.");
            }
            Collection<Employees> employeesCollectionOrphanCheck = currencies.getEmployeesCollection();
            for (Employees employeesCollectionOrphanCheckEmployees : employeesCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Currencies (" + currencies + ") cannot be destroyed since the Employees " + employeesCollectionOrphanCheckEmployees + " in its employeesCollection field has a non-nullable currency field.");
            }
            Collection<Expenses> expensesCollectionOrphanCheck = currencies.getExpensesCollection();
            for (Expenses expensesCollectionOrphanCheckExpenses : expensesCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Currencies (" + currencies + ") cannot be destroyed since the Expenses " + expensesCollectionOrphanCheckExpenses + " in its expensesCollection field has a non-nullable currency field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(currencies);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Currencies> findCurrenciesEntities() {
        return findCurrenciesEntities(true, -1, -1);
    }

    public List<Currencies> findCurrenciesEntities(int maxResults, int firstResult) {
        return findCurrenciesEntities(false, maxResults, firstResult);
    }

    private List<Currencies> findCurrenciesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Currencies.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Currencies findCurrencies(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Currencies.class, id);
        } finally {
            em.close();
        }
    }

    public int getCurrenciesCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Currencies> rt = cq.from(Currencies.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
